import {asyncRouterMap,constantRouterMap} from "@/config/router.config";

const permission = {
    state: {
        routers: constantRouterMap,
        addRouters: [],
        menus: []
    },
    mutations: {
        SET_ROUTERS: (state,data) =>{
            state.addRouters = data;
            state.routers = constantRouterMap.concat(data);
        }
    },
    actions: {
        generateRoutes({commit},data){
            return new Promise(resolve => {
                console.log('-----mutations---data----', data)
                let { roles } = data;
                let accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
                console.log('-----mutations---accessedRouters----', accessedRouters)
                commit('SET_ROUTERS',accessedRouters);
                resolve();
            });
        },
        updateAppRouter({commit},routes) {
            return new Promise(resolve => {
                let {constRoutes} = routes;
                commit('SET_ROUTERS',constRoutes);
                resolve();
            });
        }
    }
}

function filterAsyncRouter(routerMap,roles){
    return routerMap.filter(route => {
        if (hasPermission(roles.permissionList, route)) {
            if (route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children, roles);
            }
            return true;
        }
        return false;
    });
}

function hasPermission(permissionList, route){
    if(route.meta && route.meta.permission){
        let flag = -1
        for(let i = 0,len = permissionList.length; i<len; i++){
            flag = route.meta.permission.indexOf(permissionList[i]);
            if(flag >=0){
                return
            }
        }
        return false;
    }
    return  true;
}


export default permission;
